from rest_framework import status
from rest_framework.views import APIView
from celery_tasks.email.tasks import send_verify_email

from users.models import User
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView,RetrieveAPIView,UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework import serializers
from . import serialisers


class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        instance.email = validated_data['email']
        instance.save()
        #生成verify_url
        verify_url = instance.generate_verify_email_url()
        #在响应结果之前，异步发送邮件给用户
        send_verify_email.delay(instance.email,verify_url)

        return instance
class EmailView(UpdateAPIView):
    '''添加邮件的后端'''
    #指定序列化器
    serializer_class = serialisers.EmailSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self,*args,**kwargs):
        return self.request.user
class UserDetailView(RetrieveAPIView):
    '''提供用户登录信息'''
    #验证当前是否是登录状态
    #Isauthenticated : 会根据DRF配置的身份验证系统进行身份验证，判断是否登录的状态
    serializer_class = serialisers.UserDetailSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        '''返回当前登录用户的信息
        能够通过 permission_classes 的验证，说明是登录用户在访问的视图
        '''
        return self.request.user
class UserView(CreateAPIView):
    '''注册'''
    serializer_class = serialisers.CreateUserSerializer
class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)

class UsernameCountView(APIView):
    """
    用户名数量
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)
#验证邮箱连接
# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})
